<?php

namespace Qwadmin\Model;

class WarningModel extends ApiModel {

	public function dataWarning() {
		set_time_limit(0);
		$data = M('purchorder_line')->alias('pl')->where( ' pl.`sku` != "" ' )
									->field('distinct pl.sku,(SELECT SUM(num) FROM `zt_purchorder_line` WHERE `sku` = pl.sku) AS num')
									->order('pl.date_purch DESC')->select();
		foreach( $data as $key => $value ) {
			$this->_checkStockNum( $value['sku'] , $value['num'] );
			//$key == 8 ? die : '';
		}
	}


	/**
	 * 统计批次号库存数量
	 */
	private function _checkStockNum( $sku , $num) {
		if( !$sku ) return '';
		//查询产品销售库存
		$order_num = 0;
		$data = M('order_line')->where(array('sku' => $sku))->select();
		foreach( $data as $key => $value ) {
			$order_num += $value['num'];
		}
		//查询产品移动库存
		$data = M('stock_moveline')->where(array('sku' => $sku ) )->select();
		$stock_num = 0;
		foreach( $data as $key => $value ) {
			$stock_num += $value['qty_act'];
		}
		if( $num - $order_num != $stock_num ) {
			$stock_nums = $num - $order_num - $stock_num;
			if( !$stock_warning_data = M('stock_warning')->where(array('sku' => $sku))->find() ) {
				M('stock_warning')->add(array('sku' => $sku , 'info' => ($stock_nums < 0 ? '多出库存【'.$stock_nums.'】' : '少库存【'.abs( $stock_nums ).'】' )));
			} else {
				M('stock_warning')->save(array('id' => $stock_warning_data['id'] , 'info' => ($stock_nums < 0 ? '多出库存【'.$stock_nums.'】' : '少库存【'.abs( $stock_nums ).'】' )));
			}
		}
	}
}